package notice

import (
	"gddgame.cc/galaxy/asteroid"
	"gddgame.cc/galaxy/binocle/logic"
)

type AgentNoticer interface {
	SendNotice(publish string, data map[string]interface{})
}

type agentNotice struct {
	observer logic.Observer
}

func newAgentNotice(observer logic.Observer, subscriber asteroid.Sub) *agentNotice {
	s := &agentNotice{
		observer: observer,
	}
	return s
}
func (n *agentNotice) SendNotice(publish string, data map[string]interface{}) {
	//fmt.Println("agent notice", publish, data)
	n.observer.PublishPipe().List(publish, data).Send("notice")
}

type NoticeHandler func(publish string, data map[string]interface{})
type CoreNoticer interface {
	BindNoticeHandler(handler NoticeHandler)
}
type coreNotice struct {
	watcher *logic.WatcherInstance
	handler NoticeHandler
}

func newCoreNotice(watcher *logic.WatcherInstance) *coreNotice {
	s := &coreNotice{
		watcher: watcher,
	}
	watcher.Watching("notice", func(message asteroid.Message) {
		observer := message.GetOrigin()
		node := message.GetFrom()
		publish := message.Data().(string)
		data := message.Read(1).(map[string]interface{})
		if _, ok := data["server"]; !ok {
			data["server"] = observer
		}
		if _, ok := data["node"]; !ok {
			data["node"] = node
		}
		//fmt.Println("core notice", publish, data)
		if s.handler == nil {
			return
		}
		s.handler(publish, data)
	})
	return s
}

func (s *coreNotice) BindNoticeHandler(handler NoticeHandler) {
	s.handler = handler
}
